package a.netty.client;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@ChannelHandler.Sharable
public class HttpClientChannelHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        URI uri = new URI("http://127.0.0.1:8080");
        String msg = "Are you ok?";
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes(StandardCharsets.UTF_8)));

        // 构建http请求
//        request.headers().set(HttpHeaderNames.HOST, "127.0.0.1");
//        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(request.content().readableBytes()));
        // 发送http请求
        ctx.channel().writeAndFlush(request);
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse response) {
        System.out.println("Received HTTP Response");
        System.out.println("远程地址：" + ctx.channel().remoteAddress());
        System.out.println("client - HttpClientChannelHandler.messageReceived");
        System.out.println(response);
        System.out.println(response.content().toString(CharsetUtil.UTF_8));
        ctx.fireChannelRead(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("HTTP_CLIENT_HANDLER_ERROR::" + cause.getMessage());
        ctx.close();
    }
}

